// 全局变量
let currentData = null;
let timeChart = null;
let spectrumChart = null;
let envelopeChart = null;
let zoomLevel = 1;
let startIndex = 0;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    setupDragAndDrop();
    setupFileInput();
});

// 拖拽上传设置
function setupDragAndDrop() {
    const dropZone = document.getElementById('dropZone');
    
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('border-blue-500');
    });
    
    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('border-blue-500');
    });
    
    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('border-blue-500');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFile(files[0]);
        }
    });
}

// 文件输入设置
function setupFileInput() {
    const fileInput = document.getElementById('fileInput');
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            handleFile(e.target.files[0]);
        }
    });
}

// 处理上传文件
function handleFile(file) {
    if (!file.name.endsWith('.mat')) {
        showUploadStatus('请选择.mat格式的文件', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    showUploadStatus('正在处理文件...', 'info');
    
    fetch('http://localhost:5000/api/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showUploadStatus(data.error, 'error');
        } else {
            currentData = data;
            showUploadStatus('文件处理成功！', 'success');
            displayFeatures(data.features);
            createCharts(data);
            document.getElementById('featuresSection').classList.remove('hidden');
        }
    })
    .catch(error => {
        showUploadStatus('上传失败: ' + error.message, 'error');
    });
}

// 显示上传状态
function showUploadStatus(message, type) {
    const statusDiv = document.getElementById('uploadStatus');
    statusDiv.className = `mt-4 text-center p-2 rounded ${type === 'error' ? 'bg-red-100 text-red-700' : type === 'success' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`;
    statusDiv.textContent = message;
}

// 显示特征值
function displayFeatures(features) {
    document.getElementById('rmsValue').textContent = features.rms.toFixed(4);
    document.getElementById('peakValue').textContent = features.peak.toFixed(4);
    document.getElementById('kurtosisValue').textContent = features.kurtosis.toFixed(4);
    document.getElementById('maxFreqValue').textContent = features.max_frequency.toFixed(2);
    document.getElementById('maxAmpValue').textContent = features.max_amplitude.toFixed(4);
}

// 创建图表
function createCharts(data) {
    // 时域波形图
    const timeCtx = document.getElementById('timeChart').getContext('2d');
    if (timeChart) timeChart.destroy();
    
    timeChart = new Chart(timeCtx, {
        type: 'line',
        data: {
            labels: data.time.map(t => t.toFixed(3)),
            datasets: [{
                label: '时域信号',
                data: data.signal,
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                borderWidth: 1,
                pointRadius: 0,
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '时域波形 (12kHz采样)'
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '时间 (s)'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '幅值'
                    }
                }
            }
        }
    });
    
    // 频谱图
    const spectrumCtx = document.getElementById('spectrumChart').getContext('2d');
    if (spectrumChart) spectrumChart.destroy();
    
    spectrumChart = new Chart(spectrumCtx, {
        type: 'line',
        data: {
            labels: data.frequency.map(f => f.toFixed(1)),
            datasets: [{
                label: '功率谱密度',
                data: data.psd,
                borderColor: 'rgb(16, 185, 129)',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                borderWidth: 1,
                pointRadius: 0,
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '频谱分析'
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '频率 (Hz)'
                    },
                    max: 6000
                },
                y: {
                    title: {
                        display: true,
                        text: 'PSD'
                    }
                }
            }
        }
    });
    
    // 包络谱图
    const envelopeCtx = document.getElementById('envelopeChart').getContext('2d');
    if (envelopeChart) envelopeChart.destroy();
    
    envelopeChart = new Chart(envelopeCtx, {
        type: 'line',
        data: {
            labels: data.envelope_frequency.map(f => f.toFixed(1)),
            datasets: [{
                label: '包络谱',
                data: data.envelope_psd,
                borderColor: 'rgb(239, 68, 68)',
                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                borderWidth: 1,
                pointRadius: 0,
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '包络谱分析'
                }
            },
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '频率 (Hz)'
                    },
                    max: 1000
                },
                y: {
                    title: {
                        display: true,
                        text: 'PSD'
                    }
                }
            }
        }
    });
}

// 缩放功能
function zoomIn() {
    if (!currentData) return;
    
    zoomLevel = Math.min(zoomLevel * 1.5, 10);
    updateChartZoom();
}

function zoomOut() {
    if (!currentData) return;
    
    zoomLevel = Math.max(zoomLevel / 1.5, 1);
    updateChartZoom();
}

function resetZoom() {
    if (!currentData) return;
    
    zoomLevel = 1;
    startIndex = 0;
    updateChartZoom();
}

function updateChartZoom() {
    if (!currentData || !timeChart) return;
    
    const totalPoints = currentData.time.length;
    const visiblePoints = Math.floor(totalPoints / zoomLevel);
    const endIndex = Math.min(startIndex + visiblePoints, totalPoints);
    
    const visibleTime = currentData.time.slice(startIndex, endIndex);
    const visibleSignal = currentData.signal.slice(startIndex, endIndex);
    
    timeChart.data.labels = visibleTime.map(t => t.toFixed(3));
    timeChart.data.datasets[0].data = visibleSignal;
    timeChart.update();
}

// 导出CSV
function exportCSV() {
    if (!currentData) return;
    
    const exportData = {
        filename: currentData.filename,
        rms: currentData.features.rms,
        peak: currentData.features.peak,
        kurtosis: currentData.features.kurtosis,
        max_frequency: currentData.features.max_frequency,
        max_amplitude: currentData.features.max_amplitude,
        time: currentData.time,
        signal: currentData.signal
    };
    
    fetch('http://localhost:5000/api/export_csv', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(exportData)
    })
    .then(response => response.blob())
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'fault_analysis_report.csv';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    })
    .catch(error => {
        alert('导出失败: ' + error.message);
    });
}

// 图表导出功能（PNG/SVG）
function exportChart(chart, format) {
    const link = document.createElement('a');
    link.download = `chart_${new Date().getTime()}.${format}`;
    
    if (format === 'png') {
        link.href = chart.toBase64Image();
    } else if (format === 'svg') {
        // SVG导出需要额外处理
        console.warn('SVG导出功能需要额外配置');
    }
    
    link.click();
}
